package com.ycxh.controller;

import com.ycxh.controller.dto.AccessTokenResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

@Controller()
@RequestMapping("/oauth")
public class OAuthController {

    @Value("${github.client.id}")
    public String clientId;

    @Value("${github.client.secret}")
    public String clientSecret;

    @Value("${github.client.redirectUri}")
    public String redirectUri;

    @Value("${gitee.client.id}")
    public String clientIdGitee;

    @Value("${gitee.client.secret}")
    public String clientSecretGitee;

    @Value("${gitee.client.redirectUri}")
    public String redirectUriGitee;

    /**
     * Spring Boot整合OAuth2实现GitHub第三方登录
     * https://www.cnblogs.com/atwood-pan/p/17787904.html
     * @param requestToken
     * @param model
     * @return
     */
    @GetMapping("/github/redirect")
    public String handleRedirect(@RequestParam("code") String requestToken, Model model) {
        // 使用RestTemplate来发送HTTP请求
        RestTemplate restTemplate = new RestTemplate();

        // 获取Token的Url
        String tokenUrl = "https://github.com/login/oauth/access_token" +
                "?client_id=" + clientId +
                "&client_secret=" + clientSecret +
                "&code=" + requestToken;

        // 使用restTemplate向GitHub发送请求，获取Token
        AccessTokenResponse tokenResponse = restTemplate.postForObject(tokenUrl, null, AccessTokenResponse.class);

        // 从响应体中获取Token数据
        String accessToken = tokenResponse.getAccessToken();

        // 携带Token向GitHub发送请求
        String apiUrl = "https://api.github.com/user";
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "token " + accessToken);
        HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
        ResponseEntity<String> response = restTemplate.exchange(apiUrl, HttpMethod.GET, entity, String.class);
        model.addAttribute("userData", response.getBody());

        return "home-nav/index";
    }

    /**
     * Java、springboot实现Gitee登录
     * https://blog.csdn.net/qq_41647780/article/details/119616662
     * https://www.cnblogs.com/bingo39/p/17691045.html
     *
     * https://gitee.com/api/v5/oauth_doc#/
     * @param requestToken
     * @param model
     * @return
     */
    @GetMapping("/gitee/redirect")
    public String handleRedirectGitee(@RequestParam("code") String requestToken, Model model) {
        // 使用RestTemplate来发送HTTP请求
        RestTemplate restTemplate = new RestTemplate();

        /**
         * http://127.0.0.1:8088/deploy/auth
         *
         * https://gitee.com/oauth/authorize?client_id=9195ac17e78d90e15609f5573b1d59a768934c859f5d20fc7dc57548d6f3750c&redirect_uri=http://127.0.0.1:8088/deploy/oauth/gitee/redirect&response_type=code&state=1
         *
         * http://127.0.0.1:8088/deploy/oauth/gitee/redirect?code=8d41712f74e9336409b1e1eb2fb08035a388ea8c00182ea95a6f7eaf58e8779e&state=1
         */
        // 根据code获取access_token令牌
        // 获取Token的Url
        String tokenUrl = "https://gitee.com/oauth/token?grant_type=authorization_code&code=" + requestToken
                + "&client_id=" + clientIdGitee
                + "&redirect_uri=" + redirectUriGitee
                + "&client_secret=" + clientSecretGitee;

        // 使用restTemplate向GitHub发送请求，获取Token
        AccessTokenResponse tokenResponse = restTemplate.postForObject(tokenUrl, null, AccessTokenResponse.class);

        // 从响应体中获取Token数据
        String accessToken = tokenResponse.getAccessToken();
        if (StringUtils.isNotBlank(accessToken)) {
            // 根据用户的 access token 获取当前gitee用户的详细信息
            // 携带Token向GitHub发送请求
            String apiUrl = "https://gitee.com/api/v5/user?access_token=" + accessToken;

            ResponseEntity<String> response = restTemplate.exchange(apiUrl, HttpMethod.GET, null, String.class);
            if (response.getStatusCode().equals(HttpStatus.OK)) {
                // 会拼接在url后面 http://127.0.0.1:8088/deploy/nav?userData=%7B%22id%22%3A3055730%2C%22login%22%3A%22dingyinhui%22%2C%22name%22%3A%22%E6%97%A0%E4%BA%91%E6%97%A0%E5%A3%B0%22%2C%22avatar_url%22%3A%22https%3A%2F%2Fgitee.com%2Fassets%2Fno_portrait.png%22%2C%22url%22%3A%22https%3A%2F%2Fgitee.com%2Fapi%2Fv5%2Fusers%2Fdingyinhui%22%2C%22html_url%22%3A%22https%3A%2F%2Fgitee.com%2Fdingyinhui%22%2C%22remark%22%3A%22%22%2C%22followers_url%22%3A%22https%3A%2F%2Fgitee.com%2Fapi%2Fv5%2Fusers%2Fdingyinhui%2Ffollowers%22%2C%22following_url%22%3A%22https%3A%2F%2Fgitee.com%2Fapi%2Fv5%2Fusers%2Fdingyinhui%2Ffollowing_url%7B%2Fother_user%7D%22%2C%22gists_url%22%3A%22https%3A%2F%2Fgitee.com%2Fapi%2Fv5%2Fusers%2Fdingyinhui%2Fgists%7B%2Fgist_id%7D%22%2C%22starred_url%22%3A%22https%3A%2F%2Fgitee.com%2Fapi%2Fv5%2Fusers%2Fdingyinhui%2Fstarred%7B%2Fowner%7D%7B%2Frepo%7D%22%2C%22subscriptions_url%22%3A%22https%3A%2F%2Fgitee.com%2Fapi%2Fv5%2Fusers%2Fdingyinhui%2Fsubscriptions%22%2C%22organizations_url%22%3A%22https%3A%2F%2Fgitee.com%2Fapi%2Fv5%2Fusers%2Fdingyinhui%2Forgs%22%2C%22repos_url%22%3A%22https%3A%2F%2Fgitee.com%2Fapi%2Fv5%2Fusers%2Fdingyinhui%2Frepos%22%2C%22events_url%22%3A%22https%3A%2F%2Fgitee.com%2Fapi%2Fv5%2Fusers%2Fdingyinhui%2Fevents%7B%2Fprivacy%7D%22%2C%22received_events_url%22%3A%22https%3A%2F%2Fgitee.com%2Fapi%2Fv5%2Fusers%2Fdingyinhui%2Freceived_events%22%2C%22type%22%3A%22User%22%2C%22blog%22%3Anull%2C%22weibo%22%3Anull%2C%22bio%22%3Anull%2C%22public_repos%22%3A3%2C%22public_gists%22%3A0%2C%22followers%22%3A3%2C%22following%22%3A0%2C%22stared%22%3A247%2C%22watched%22%3A12%2C%22created_at%22%3A%222019-01-08T14%3A29%3A32%2B08%3A00%22%2C%22updated_at%22%3A%222024-01-17T08%3A51%3A17%2B08%3A00%22%2C%22email%22%3Anull%7D
                model.addAttribute("userData", response.getBody());
            }
        }

        // 跳转到首页 工作台
        return "redirect:/nav";
    }

}
